package com.yj_app.qualitytest.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hu_sir.sweet_dialog_reversion.SweetAlertDialog;
import com.rengwuxian.materialedittext.MaterialAutoCompleteTextView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yj_app.qualitytest.R;
import com.yj_app.qualitytest.adapter.ArrayAdapter;
import com.yj_app.qualitytest.adapter.BCadapter;
import com.yj_app.qualitytest.base.BaseFragment;
import com.yj_app.qualitytest.common.Config;
import com.yj_app.qualitytest.info.BcInfo;
import com.yj_app.qualitytest.info.HeadBoyInfo;
import com.yj_app.qualitytest.info.QLineInfo;
import com.yj_app.qualitytest.info.QScoreInfo;
import com.yj_app.qualitytest.info.QrelationshipInfo;
import com.yj_app.qualitytest.info.TeamInfo;
import com.yj_app.qualitytest.info.WorkSpaceInfo;
import com.yj_app.qualitytest.util.DateUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　 ┏┓　  ┏┓
 * 　　┏┛┻━━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━代码无bug━━━━━━
 * <p>
 * Copyright (C), 2015-2019-10-28, 石家庄云捷软件科技有限公司
 *
 * @ProjectName: BiaoChengFragment.java
 * @Package: com.yj_app.qualitytest.fragment
 * @ClassName: BiaoChengFragment
 * @Description: TODO  标称页面
 * @Author: Hu_Sir
 * @CreateDate: 2019-10-28 - 08:25
 * @UpdateUser: ?
 * @UpdateDate: 2019-10-28 - 08:25
 * @UpdateRemark: todo
 */
public class BiaoChengFragment extends BaseFragment {
    Bundle bundle;
    @BindView(R.id.work_shop_name)
    TextView workShopName;
    @BindView(R.id.sc_line)
    MaterialAutoCompleteTextView scLine;
    @BindView(R.id.zr_search)
    MaterialAutoCompleteTextView zrSearch;
    @BindView(R.id.bz_team)
    AppCompatSpinner bzTeam;
    @BindView(R.id.machine_no)
    AppCompatSpinner machineNo;
    @BindView(R.id.bzfs_spinner)
    AppCompatSpinner bzfsSpinner;
    @BindView(R.id.czfs_spinner)
    AppCompatSpinner czfsSpinner;


    ArrayAdapter<QLineInfo> searchAdapter;

    List<HeadBoyInfo> headBoyInfos = new ArrayList<>();//主任数据源
    ArrayAdapter<HeadBoyInfo> searchHeadboyAdapter;//主任适配器
    HeadBoyInfo headBoyInfo;

    TeamInfo teamInfo;//已选择的班组
    int teamSelectPos;//进入页面后班组初始化的pos


    QLineInfo qLineInfo;//选中的生产线
    WorkSpaceInfo workSpaceInfo;//选中的车间

    @BindView(R.id.cz_count)
    TextView czCount;
    @BindView(R.id.cz_wc)
    TextView czWc;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    View diaview;
    MaterialEditText mCount,mWuCha;


    public static BiaoChengFragment getIntance() {
        BiaoChengFragment biaoChengFragment = new BiaoChengFragment();
        return biaoChengFragment;
    }

    public BiaoChengFragment setBundle(Bundle bundle) {
        this.bundle = bundle;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        if (rootView == null) {
            rootView = View.inflate(getContext(), R.layout.fragment_biaocheng, null);
        }
        ButterKnife.bind(this, rootView);

        initView();
        initEvent();
        return rootView;
    }

    private void initEvent() {
        /*生产线*/
        scLine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                qLineInfo = (QLineInfo) adapterView.getItemAtPosition(i);
                workSpaceInfo = LitePal.where("cjcode = ?", qLineInfo.getCjcode()).findFirst(WorkSpaceInfo.class);
                workShopName.setText(workSpaceInfo != null ? workSpaceInfo.getCjname() : "无法获取");
                if (workSpaceInfo != null) {
                    //班组和车间不为空
                    //设置主任
                    if (workSpaceInfo != null && bzTeam.getSelectedItem() != null) {
                        TeamInfo teamInfo = (TeamInfo) bzTeam.getSelectedItem();
                        QrelationshipInfo qrelationshipInfo = LitePal.where("cjcode = ? and cteam = ?", workSpaceInfo.getCjcode(), teamInfo.getGname()).findFirst(QrelationshipInfo.class);
                        if (qrelationshipInfo == null) {
                            qrelationshipInfo = LitePal.where("cjcode = ? and cteam = ?", qLineInfo.getScxcode(), teamInfo.getGname()).findFirst(QrelationshipInfo.class);
                        }
                        if (qrelationshipInfo != null) {
                            headBoyInfo = new HeadBoyInfo();
                            headBoyInfo.setNickname(qrelationshipInfo.getNICKNAME());
                            headBoyInfo.setUsercode(qrelationshipInfo.getUSERCODE());
                            zrSearch.setText(qrelationshipInfo.getNICKNAME());
                            baseActivity.toastError(qrelationshipInfo.getNICKNAME());
                        }
                    }
                }


            }
        });

        bCadapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BcInfo bcInfo= (BcInfo) adapter.getItem(position);
                if (mCount != null) {
                    mCount.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(((Activity)getActivity()).getWindow().getDecorView(), InputMethodManager.SHOW_FORCED);
                }
                mCount.setText(bcInfo.getCount());
                mWuCha.setText(bcInfo.getWucha());
                new SweetAlertDialog(getContext(), SweetAlertDialog.CONTENTVIEW_TYPE).setmContentView(diaview)
                        .setTitleText("请输入次数和误差").setConfirmText("确定").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                if (TextUtils.isEmpty(mCount.getText().toString().trim())) {
                                    baseActivity.toastError("请填写称重次数");
                                    return;
                                }
                                if (TextUtils.isEmpty(mWuCha.getText().toString().trim())) {
                                    baseActivity.toastError("请输入误差数量");
                                    return;
                                }
                                if (!TextUtils.equals(bcInfo.getCount(),mCount.getText().toString().trim())||
                                        !TextUtils.equals(bcInfo.getWucha(),mWuCha.getText().toString().trim())){
                                    BcInfo bcSearch=LitePal.where("bcinfo.itemname = ?",bcInfo.getItemname()).findFirst(BcInfo.class);
                                    bcInfo.setCount(mCount.getText().toString().trim());
                                    bcInfo.setWucha(mWuCha.getText().toString().trim());

                                    bcSearch.setCount(mCount.getText().toString().trim());
                                    bcSearch.setWucha(mWuCha.getText().toString().trim());

                                    adapter.notifyItemChanged(position);
                                    bcSearch.update(bcSearch.getId());

                                }

                                sweetAlertDialog.dismiss();
                                ((ViewGroup) diaview.getParent()).removeView(diaview);

                            }
                        }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        ((ViewGroup) diaview.getParent()).removeView(diaview);
                    }
                }).show();



            }
        });
        zrSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                headBoyInfo = (HeadBoyInfo) parent.getItemAtPosition(position);


            }
        });


    }

    private void initView() {
        initScLineAdapter();
        initZrAdapter();
        initTeam();
        initChengZhongadapter();
        initBcadapter();
        initDialogView();
    }
    private void initDialogView() {


         diaview = View.inflate(getContext(), R.layout.dialog_bc, null);
         mCount = diaview.findViewById(R.id.me_count);
         mWuCha = diaview.findViewById(R.id.me_wucha);
    }

    List<BcInfo> bcInfos;
    BCadapter bCadapter;

    private void initBcadapter() {
        bcInfos = LitePal.order("id").find(BcInfo.class);
        bCadapter = new BCadapter(R.layout.item_bc, bcInfos);
        myRecy.setLayoutManager(new LinearLayoutManager(getContext()));
        myRecy.setAdapter(bCadapter);


    }

    /*初始化称重适配器*/
    private void initChengZhongadapter() {
        List<QScoreInfo> checkbzlxList = LitePal.where("qscoreinfo.ccode LIKE ? ", bundle.getString(Config.P_ID) + "04%").find(QScoreInfo.class);
        ArrayAdapter<QScoreInfo> adapter_class = new ArrayAdapter<QScoreInfo>(getContext(), R.layout.simple_list_item_1, checkbzlxList);
        czfsSpinner.setAdapter(adapter_class);
    }

    /*初始化班组*/
    private void initTeam() {
        teamInfo = (TeamInfo) bundle.getSerializable(Config.TEAM_INFO);
        teamSelectPos = bundle.getInt(Config.TEAM_POSTION);
        List<TeamInfo> teamInfoList = LitePal.order("id").find(TeamInfo.class);
        ArrayAdapter<TeamInfo> teamInfoArrayAdapter = new ArrayAdapter<TeamInfo>(getContext(), R.layout.simple_list_item_1, teamInfoList);
        bzTeam.setAdapter(teamInfoArrayAdapter);
        bzTeam.setSelection(teamSelectPos);

    }

    /*主任适配器*/
    private void initZrAdapter() {
        List<HeadBoyInfo> headBoyInfos = LitePal.findAll(HeadBoyInfo.class);
        searchHeadboyAdapter = new ArrayAdapter(getContext(), R.layout.simple_list_item_1, headBoyInfos);
        zrSearch.setAdapter(searchHeadboyAdapter);
        showDropDown(zrSearch);
    }

    /*生产线适配器*/
    private void initScLineAdapter() {
        List<QLineInfo> qLineInfos = LitePal.findAll(QLineInfo.class);
        searchAdapter = new ArrayAdapter(getContext(), R.layout.simple_list_item_1, qLineInfos);
        scLine.setAdapter(searchAdapter);
        showDropDown(scLine);

    }



    @OnClick({R.id.cz_count, R.id.cz_wc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cz_count:
            case R.id.cz_wc:
                if (qLineInfo == null&&headBoyInfo == null) {
                    baseActivity.toastError("请选择生产线或者请选择车间主任");
                    return;
                }
                if (mCount != null) {
                    mCount.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(((Activity)getActivity()).getWindow().getDecorView(), InputMethodManager.SHOW_FORCED);
                }
                new SweetAlertDialog(getContext(), SweetAlertDialog.CONTENTVIEW_TYPE).setmContentView(diaview)
                        .setTitleText("请输入次数和误差").setConfirmText("确定").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                if (TextUtils.isEmpty(mCount.getText().toString().trim())) {
                                    baseActivity.toastError("请填写称重次数");
                                    return;
                                }
                                if (TextUtils.isEmpty(mWuCha.getText().toString().trim())) {
                                    baseActivity.toastError("请输入误差数量");
                                    return;
                                }

                                save(mCount.getText().toString(),mWuCha.getText().toString());
                                sweetAlertDialog.dismiss();
                                ((ViewGroup) diaview.getParent()).removeView(diaview);

                            }
                        }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        ((ViewGroup) diaview.getParent()).removeView(diaview);
                    }
                }).show();


                break;
        }
    }

    private void save(String mcount, String mwucha) {

        if (qLineInfo != null && headBoyInfo != null && workSpaceInfo != null) {
            BcInfo bcInfo =new BcInfo();
            bcInfo.setCjname(workSpaceInfo.getCjname());
            bcInfo.setCjcode(workSpaceInfo.getCjcode());

            bcInfo.setqLineId(qLineInfo.getScxcode());
            bcInfo.setScxname(qLineInfo.getScxname());

            bcInfo.setNickname(headBoyInfo.getNickname());
            bcInfo.setUsercode(headBoyInfo.getUsercode());

            teamInfo= (TeamInfo) bzTeam.getSelectedItem();
            bcInfo.setGcode(teamInfo.getGcode());

            bcInfo.setMachino(machineNo.getSelectedItem().toString());

            bcInfo.setBzfs(bzfsSpinner.getSelectedItem().toString());

            QScoreInfo qScoreInfo= (QScoreInfo) czfsSpinner.getSelectedItem();
            bcInfo.setqScoreInfoId(qScoreInfo.getItemid());
            bcInfo.setItemname(qScoreInfo.getItemname());

            bcInfo.setCount(mcount);

            bcInfo.setWucha(mwucha);
            bcInfo.setTime(DateUtils.convertToString(System.currentTimeMillis(),DateUtils.TIME_FORMAT));

            bcInfos.add(0,bcInfo);
            bcInfo.save();

            czCount.setText(mcount);
            czWc.setText(mwucha);

            bCadapter.setNewData(bcInfos);


        }
    }
}
